<template>
    <div class="image d-flex flex-column">
        <transition
            mode="out-in"
            name="rotate"
            @after-enter="viewerLoad">
            <div class="view-container" v-if="viewing && mode == constant.CARD" :key="constant.CARD">
                <moving v-bind="{start : 0, end: length - 1, index: viewing.index, loopable: true, view}"/>
                <imageCard
                    v-if="viewing"
                    :doc="viewing.doc"
                    :key="viewing.doc._id"
                    @close="viewing=null;"
                    @rename="doc => $emit('rename', doc)"
                    @addExtendInfo="doc => $emit('addExtendInfo', doc)"
                    @editExtendInfo="(doc, info) => $emit('editExtendInfo', doc, info)"
                    @removeExtendInfo="(doc, info) => $emit('removeExtendInfo', doc, info)"
                >
                    <footerBar slot="footer-bar" v-bind="{
                        toggleMode, toggleItem, itemChosed, viewing,
                        choosing, chosedArr, length, loadedNum: ei
                    }" />
                </imageCard>
            </div>
            <div class="view-container" v-else-if="viewing && mode == constant.VIEWER" :key="constant.VIEWER">
                <moving v-bind="{start : 0, end: doubleColumn ? length - 1 : length, index: viewing.index, loopable: true, view}"/>
                <imageViewer
                    :class="[couldDoubleColumn ? 'col-one' : '']"
                    :src="viewing.doc.baseInfo.src"
                    :plugins="viewerPlugin"
                    :viewMode.sync="viewerMode"
                    ref="imageViewer"
                    @close="viewing=null;"
                >
                    <template slot="footer-bar">
                        <footerBar v-bind="{
                            toggleMode, toggleItem, itemChosed, viewing,
                            choosing, chosedArr, length, loadedNum: ei
                        }" />
                        <button class="btn btn-sm btn-link p-1 mx-2"
                            :class="[doubleColumn ? 'text-info' : 'text-muted']"
                            @click="doubleColumn = !doubleColumn, $nextTick(() => $refs.imageViewer.initImage())"
                            v-tooltip title='双栏显示'>
                            <i class="material-icons align-middle" >compare</i>
                        </button>
                    </template>
                </imageViewer>
                <imageViewer
                    v-if="couldDoubleColumn"
                    :class="[couldDoubleColumn ? 'col-two' : '']"
                    :src="viewingNextDoc ? viewingNextDoc.baseInfo.src : viewing.doc.baseInfo.src"
                    :plugins="viewerPlugin"
                    :viewMode.sync="viewerMode"
                    ref="imageViewer_next"
                    @close="viewing=null;"
                >
                    <footerBar slot="footer-bar" v-bind="{toggleMode, toggleItem, itemChosed,
                        viewing: viewingNextDoc ? {
                            index: viewing.index + 1,
                            doc: viewingNextDoc
                        } : viewing, choosing,
                        chosedArr, length, loadedNum: ei
                    }" />
                </imageViewer>
            </div>
        </transition>
        <loading :active.sync="isLoading"
        :can-cancel="false"
        backgroundColor='transparent'
        loader='dots'
        :is-full-page="false"></loading>
        <div class="controller d-flex p-2 align-items-center">
            <template v-if="editable">
                <button class="btn btn-sm btn-link text-info p-1 mr-1" @click="$emit('searchByImage')" v-tooltip title='搜索图片'>
                    <i class="material-icons align-middle">image_search</i>
                </button>
                <button class="btn btn-sm btn-link text-info p-1 mr-1" @click="$emit('upload')" v-tooltip title='上传图片'>
                    <i class="material-icons align-middle">cloud_upload</i>
                </button>
                
                <button class="btn btn-sm btn-link text-muted p-1 mr-1" @click="toggleChooseMode" v-tooltip title='选择图片' v-if="!choosing">
                    <i class="material-icons align-middle" >select_all</i>
                </button>
                <template v-else>
                    <button class="btn btn-sm btn-link text-danger p-1 mr-1" @click="removeChosed" v-tooltip title='从当前目录移除' v-if="chosedArr.length">
                        <i class="material-icons align-middle">delete</i>
                    </button>
                    <button class="btn btn-sm btn-link text-success p-1 mr-1" @click="copyChosed" v-tooltip title='复制到...' v-if="chosedArr.length">
                        <i class="material-icons align-middle">move_to_inbox</i>
                    </button>
                    <button class="btn btn-sm btn-link text-success p-1 mr-1" @click="moveChosed" v-tooltip title='移动到...' v-if="chosedArr.length">
                        <i class="material-icons align-middle">send</i>
                    </button>
                    <button class="btn btn-sm btn-link text-muted p-1 mr-1" @click="toggleChoosedArr" v-tooltip title='反选'>
                        <i class="material-icons align-middle" >compare_arrows</i>
                    </button>
                    
                    <button class="btn btn-sm btn-link text-muted p-1 mr-1" @click="toggleChooseMode" v-tooltip title='取消'>
                        <i class="material-icons align-middle" >close</i>
                    </button>
                </template>
                <div class="input-group w-auto">
                    <div class="input-group-prepend">
                      <span class="input-group-text">分组：</span>
                    </div>
                    <select class="custom-select w-auto" v-model="groupType">
                        <option value="" selected>无</option>
                        <option value="width">宽度</option>
                        <option value="height">高度</option>
                        <option value="aspectRatio">宽高比</option>
                        <option value="size">图片大小</option>
                        <option value="createDate">创建日期</option>
                        <option value="lastModifyDate">最后修改日期</option>
                        <option value="similary">相似度</option>
                    </select>
                    <div class="input-group-addon" style="cursor: pointer; margin-left: -2px" v-if="groupedInfo" v-tooltip title="组别排序" @click="sortGroupDirection *= -1">
                        <span class="input-group-text text-success bg-white">
                            <i class="material-icons align-middle" v-if="sortGroupDirection == 1">arrow_upward</i>
                            <i class="material-icons align-middle" v-else-if="sortGroupDirection == -1">arrow_downward</i>
                        </span>
                    </div>
                </div>

                <button class="btn btn-sm btn-link text-success p-1 mr-1" v-if="groupedInfo" v-tooltip title="组内排序"  @click="sortImageDirection = sortImageDirection == 1 ? -1 : sortImageDirection + 1">
                    <i class="material-icons align-middle" v-if="sortImageDirection == 1">arrow_upward</i>
                    <i class="material-icons align-middle" v-else-if="sortImageDirection == -1">arrow_downward</i>
                    <i class="material-icons align-middle" v-else >sort</i>
                </button>
                <button class="btn btn-sm btn-link text-success p-1 mr-1" v-else v-tooltip title="按名字排序" @click="sortImageDirection = sortImageDirection == 1 ? -1 : sortImageDirection + 1">
                    <i class="material-icons align-middle" v-if="sortImageDirection == 1">arrow_upward</i>
                    <i class="material-icons align-middle" v-else-if="sortImageDirection == -1">arrow_downward</i>
                    <i class="material-icons align-middle" v-else>sort</i>
                </button>
                        
                
                <!-- <button class="btn btn-sm btn-link p-1 mr-1 text-muted" v-tooltip title='按相似度分组' @click="toggleGrouped" v-if="!groupedInfo">
                    <i class="material-icons align-middle" >collections</i>
                </button>
                <button class="btn btn-sm btn-link p-1 mr-1 text-muted" v-tooltip title='取消分组' @click="toggleGrouped" v-else>
                    <i class="material-icons align-middle" >collections</i>
                </button> -->
            </template>
            <div class="info d-inline-block ml-auto mr-2 p-1">
                <indexInfo v-bind="{choosing, chosedArr, viewing, length, loadedNum: ei}"/>
            </div>
        </div>
        <div class="list-container flex-grow-1">
            <div class="list">
                <template v-if="!groupedInfo">
                    <div class="item d-inline-block m-2 img-thumbnail rounded p-0"
                        v-for="(doc, index) in docs"
                        :class="{active: choosing ? itemChosed[index] : viewing && viewing.doc._id == doc._id}"
                    >
                        <button class="btn btn-sm btn-link text-info m-1 p-0" style="position: absolute; top: 0; right: 0; z-index: 1;" >
                            <i class="material-icons align-middle" v-if="choosing" @click="view(index)">image</i>
                        </button>
                        <lazyImg :image="{src: doc.baseInfo.src + '?thumb=true', alt: doc.baseInfo.name}" :size="150" :key="doc._id" @smart-click="itemClick(index)"></lazyImg>
                    </div>
                </template>
                <template v-else v-for="val in loadedGroupedContents">
                    <div class="grouped-title text-muted m-2 py-3">{{val.title}}</div>
                    <div class="item d-inline-block m-2 img-thumbnail rounded p-0"
                        v-for="(doc, index) in val.content"
                        :class="{active: choosing ? itemChosed[val.offset+index] : viewing && viewing.doc._id == doc._id}"
                    >
                        <button class="btn btn-sm btn-link text-info m-1 p-0" style="position: absolute; top: 0; right: 0; z-index: 1;" >
                            <i class="material-icons align-middle" v-if="choosing" @click="view(val.offset + index)">image</i>
                        </button>
                        <lazyImg :image="{src: doc.baseInfo.src + '?thumb=true', alt: doc.baseInfo.name}" :size="150" :key="doc._id" @smart-click="itemClick(val.offset + index)"></lazyImg>
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>

<script type="text/javascript">
import _ from 'lodash'
import Scrollbar from 'smooth-scrollbar'

import $ from 'jquery'

import jqAjax from '../plugin/jqAjax'
import {constant as ajaxConstant} from '../plugin/jqAjax'

import lazyImg from './lazy-img'
import imageCard from './image-card'
import {constant as imageCardConstant} from './image-card'
import imageViewer from './image-viewer'
import {constant as imageViewerConstant, scaleController, dragController, resizeController} from './image-viewer'

import Loading from 'vue-loading-overlay';
import 'vue-loading-overlay/dist/vue-loading.css';

var constant = Object.assign({
    CARD: 'card',
    VIEWER: 'viewer',

}, ajaxConstant, imageCardConstant, imageViewerConstant);

const moving = {
    props: ['start', 'end', 'index', 'loopable', 'view'],
    template: `
        <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;">
            <button class="prev btn btn-outline-info ml-2 mr-auto rounded-circle"
                :disabled="prevIndex == -1"
                @click="view(prevIndex)"
                :style="[styleSheet.btn, styleSheet.prev]"
            >
                <i class="material-icons align-middle">navigate_before</i>
            </button>
            <button class="next btn btn-outline-info ml-auto mr-2  rounded-circle"
                :disabled="nextIndex == -1"
                @click="view(nextIndex)"
                :style="[styleSheet.btn, styleSheet.next]"
            >
                <i class="material-icons align-middle">navigate_next</i>
            </button>
        </div>
    `,
    computed: {
        prevIndex() {
            if (!this.loopable && this.index <= this.start) {
                return -1;
            } else if (this.loopable) {
                return this.index <= this.start ? this.end - 1 : this.index - 1;
            } else {
                return -1;
            }
        },
        nextIndex() {
            if (!this.loopable && this.index >= this.end - 1) {
                return -1;
            } else if (this.loopable) {
                return this.index >= this.end - 1 ? this.start : this.index + 1;
            } else {
                return -1;
            }
        },
        styleSheet() {
            return {
                btn: {
                    position: 'absolute',
                    top: '0',
                    bottom: '0',
                    zIndex: '2',
                    width: '2rem',
                    height: '2rem',
                    lineHeight: '2rem',
                    textAlign: 'center',
                    padding: '0',
                    margin: 'auto',
                },
                prev: { left: 0 },
                next: {right: 0}
            }
        }
    }
}

const indexInfo = {
    props: ['choosing', 'chosedArr', 'viewing', 'length', 'loadedNum'],
    template: `
        <div class="d-inline-block align-middle">
            <template v-if="choosing">
                <span class="text-muted mr-2 align-middle">已选择</span><span class="text-info">{{chosedArr.length}}</span>
            </template>
            <template v-else>
                <template v-if="!viewing">
                    <span class="text-muted mr-2 align-middle">已加载</span><span class="text-info">{{loadedNum}}</span>
                </template>
                <template v-else>
                    <span class="text-muted mr-2 align-middle"></span><span class="text-info">{{viewing.index + 1}}</span>
                </template>
            </template>
            /
            <span class="text-muted">{{length}}</span>
        </div>
    `
}

const footerBar = {
    props: ['toggleMode', 'toggleItem', 'itemChosed', 'viewing', 'choosing', 'chosedArr', 'length', 'loadedNum'],
    components: {indexInfo},
    template: `
        <div class="d-inline-block align-middle">
            <button
                type="button"
                class="btn btn-sm btn-outline-info mx-1"
                @click="toggleMode"
            >
                <i class="material-icons align-middle">compare_arrows</i>
            </button>
            <button
                type="button"
                class="btn btn-sm bg-transparent text-info mx-1"
                @click="toggleItem(viewing.index)"
                v-if="choosing"
            >
                <i class="material-icons align-middle">{{itemChosed[viewing.index] ? 'check_box' : 'check_box_outline_blank'}}</i>
            </button>
            <indexInfo v-bind="{choosing, chosedArr, viewing, length, loadedNum}"/>
        </div>
    `
}

export default {
    name: 'lazy-image',
    components: {Loading, lazyImg, imageCard, imageViewer, indexInfo, footerBar, moving},
    mixins: [jqAjax],
    props: {
        editable: {
            type: Boolean,
            default: true
        },
        content: {
            type: Array,
            required: true
        },
       
        loadOneTime: {
            type: Number,
            default: 999999999
        },
        initMode: {
            type: String,
            default: constant.CARD
        }
    },
    data() {
        var vm = this;
        return {
            doubleColumn: false,
            choosing: false,
            itemChosed: [],
            ei: 0,
            viewing: null,
            docs: [],
            backgroundLoading: false,
            mode: this.initMode,
            constant: Object.assign({}, constant),
            viewerPlugin: [scaleController, dragController, resizeController],
            viewerMode: constant.VIEW_MODE_AUTO,
            mGroupType: '',
            groupedInfo: null,
            sortGroupDirection: 1,
            sortImageDirection: 0,
            tickQueue: [],
        }
    },
    computed: {
        couldDoubleColumn() {
            return this.length && this.doubleColumn;
        },
        viewingNextDoc() {
            if (!this.viewing) {
                return null;
            }
            var i = this.viewing.index + 1;
            if (i < this.length) {
                return this.docs[i];
            } else {
                return null;
            }
        },
        isLoading() {
            return this.state == constant.LOADING && !this.backgroundLoading;
        },
        ids() {
            if (!this.groupedInfo) {
                return this.content.slice();
            } else {
                return this.groupedInfo.reduce((a, b) => {return a.push.apply(a, b.arr), a}, []);
            }
        },
        loadedGroupedContents() {
            if (!this.groupedInfo || !this.docs.length) {
                return [];
            } else {
                var i = 0, l = this.docs.length;
                return this.groupedInfo.map(x => {
                    let offset = i;
                    var val = {
                        title: x._id,
                        content: i < l ? this.docs.slice(i, i + x.arr.length) : [],
                        offset
                    };
                    i += x.arr.length;
                    return val;
                }).filter(x => x.content.length);
            }
        },
        length() {
            return this.ids.length;
        },
        chosedArr() {
            var arr = [];
            for (var i = 0; i < this.length; i++) {
                if (this.itemChosed[i]) {
                    arr.push(this.ids[i]);
                }
            }
            return arr;
        },
        groupType: {
            get() {
                return this.mGroupType;
            },
            set(nv) {
                var vm = this;
                if (nv == this.mGroupType) {
                    return;
                }
                vm.groupFor(nv);
            }
        }

    },
    methods: {
        tick() {
            var vm = this;
            vm.tickQueue.forEach(fn => fn.call(vm));
            vm.tickQueue = [];
        },
        async groupFor(nv) {
            var simpleGroupBy = function(lb, bt, sfn) {
                var t = _.groupBy(vm.docs, function(obj) {
                    return lb(obj);
                });
                var keys = Object.keys(t).sort((a, b) => (a - b) * vm.sortGroupDirection);
                return keys.map(x => {
                    return {_id: bt(x), arr: t[x].sort(
                        (a, b) => sfn(a, b) * vm.sortImageDirection
                    ).map(img => img._id)};
                });
            }, handler = {
                '': function() {
                    return null;
                },
                width() {
                    return simpleGroupBy(x => parseInt(x.baseInfo.width / 100), x => `${x}00 ~ ${x}99`, (a, b) => a.baseInfo.width - b.baseInfo.width);
                },
                height() {
                    return simpleGroupBy(x => parseInt(x.baseInfo.height / 100), x => `${x}00 ~ ${x}99`, (a, b) => a.baseInfo.height - b.baseInfo.height);
                },
                aspectRatio() {
                    return simpleGroupBy(x => parseInt(x.baseInfo.aspectRatio), x => `${x} ~ ${x}.99`, (a, b) => a.baseInfo.aspectRatio - b.baseInfo.aspectRatio)
                },
                size() {
                    return simpleGroupBy(x => parseInt(x.baseInfo.size / (1024 * 1024)), x => `${x}mb ~ ${x}.99mb`, (a, b) => a.baseInfo.size - b.baseInfo.size);
                },
                createDate() {
                    return simpleGroupBy(x => new Date(x.baseInfo.createDate).toLocaleDateString(), x => `${x}`, (a, b) => a.baseInfo.createDate - b.baseInfo.createDate);
                },
                lastModifyDate() {
                    return simpleGroupBy(x => new Date(x.baseInfo.lastModifyDate).toLocaleDateString(), x => `${x}`, (a, b) => a.baseInfo.lastModifyDate - b.baseInfo.lastModifyDate);
                },
                async similary() {
                    var res = await vm.ajaxPost(`/model/image/group/similary`, {
                        args: {
                            content: vm.content
                        }
                    });
                    if (vm.sortGroupDirection == -1) {
                        res.result.reverse();
                    }
                    return res.result;
                }
            }, vm = this;
            if (! handler.hasOwnProperty(nv)) {
                return;
            } else {
                if (nv !== 'similary') {
                    vm.reposition();
                }
                vm.mGroupType = nv;
                vm.groupedInfo = await handler[nv]();
            }
        },
        // freshGroupedInfo() {
        //     var vm = this;
        //     if (!vm.groupType || !(vm.groupType in constant.GROUPE_ARGS)) {
        //         return;
        //     }
        //     vm.ajaxPost(`/model/image/group/${groupType}`, {
        //         args: {
        //             content: vm.content,
        //             group: constant.GROUPE_ARGS[groupType].group,
        //             sort: constant.GROUPE_ARGS[groupType].sort
        //         }
        //     })
        //     .done(function(res) {
        //         vm.groupedInfo = res.result;
        //     })

        // },
        toggleChooseMode() {
            var vm = this;
            vm.choosing = !vm.choosing;
            vm.itemChosed = [];
        },
        toggleChoosedArr() {
            var arr = [];
            for (var i = 0; i < this.length; i++) {
                arr[i] = !this.itemChosed[i];
            }
            this.itemChosed = arr;
        },
        removeChosed() {
            this.$emit('remove', this.chosedArr);
        },
        moveChosed() {
            this.$emit('move', this.chosedArr);
        },
        copyChosed() {
            this.$emit('copy', this.chosedArr);
        },
        itemClick(index) {
            if (!this.choosing) {
                return this.view(index);
            } else {
                return this.toggleItem(index);
            }
        },
        toggleItem(index) {
            var old = this.itemChosed[index];
            this.$set(this.itemChosed, index, !old);
        },
        toggleMode() {
            if (this.mode == constant.CARD) {
                this.mode = constant.VIEWER;
            } else {
                this.mode = constant.CARD;
            }
            this.$emit('update:initMode', this.mode);
        },
        getMore(cb) {
            // deprecated, conflic with group and sort
            var vm = this;
            if (vm.ei == vm.length) {
                return;
            }
            var _ids = vm.ids.slice(vm.ei, vm.loadOneTime + vm.ei);
            return vm.ajaxPost('/model/image/list', {
                args: JSON.stringify({_ids})
            }).done(function(res) {
                _ids.forEach(function(_id) {
                    // 返回的结果不一定是按照_ids的顺序排列
                    var doc = res.images.find((x) => {return x._id == _id;});
                    vm.docs.push(doc);
                });
                vm.ei += _ids.length;
                vm.tick();
                cb && cb();
            });
        },
        getMoreBackground() {
            this.backgroundLoading = true;
            this.getMore();
        },
        view(i) {
            var vm = this;
            if (0 > i || i >= vm.docs.length) {
                if (vm.ei < vm.length) {
                    vm.getMore(function() {
                        vm.view(i);
                    });
                }
                return;
            }
            vm.viewing = {
                doc: vm.docs[i],
                index: i,
                $el: $(vm.list).find('.item').get(i)
            };
            
        },
        getMoreUntilFullPage() {
            // deprecated, conflic with group and sort
            var vm = this;
            if (vm.ei >= vm.length) {
                return;
            }
            vm.scrollbar.update();
            var pageHeight = vm.scrollbar.size.content.height - vm.scrollbar.offset.y;
            if (pageHeight * 0.7 < vm.scrollbar.size.container.height) {
                setTimeout(() => vm.getMore());
            }
        },
        setPadding() {
            var vm = this;
            var $list = $(vm.list), $item = $list.find('.item').eq(0);
            if (!$item.length) {
                $list.css('paddingLeft', 0);
                return;
            }
            var size = $item.outerWidth(true);
            $list.css('paddingLeft', $list.innerWidth() % size / 2);
        },
        viewerLoad() {
            var vm = this;
            if (vm.viewing && vm.mode == constant.VIEWER) {
                var arr = [this.$refs.imageViewer, this.$refs.imageViewer_next];
                arr.forEach(x => {
                    x && x.freshContainerSize();
                })
            }
        },
        sortForName() {
            var vm = this;
            var sortByName = function(a, b) {
                var a_l = a.length, b_l = b.length, c_a, c_b, n_a, n_b, s_a, e_a, s_b, e_b;
                for (var i = 0, j = 0; i < a_l && j < b_l; i++, j++) {
                    c_a = a.charCodeAt(i);
                    c_b = b.charCodeAt(j);
                    if (48 <= c_a && c_a <= 57 && 48 <= c_b && c_b <= 57) {
                        // compare number
                        e_a = s_a = i;
                        e_b = s_b = j;
                        while (48 <= c_a && c_a <= 57 && e_a < a_l) {
                            c_a = a.charCodeAt(++e_a);
                        }
                        while (48 <= c_b && c_b <= 57 && e_b < b_l) {
                            c_b = b.charCodeAt(++e_b);
                        }
                        n_a = parseInt(a.substring(s_a, e_a));
                        n_b = parseInt(b.substring(s_b, e_b));
                        if (n_a == n_b) {
                            i = e_a - 1;
                            j = e_b - 1;
                            continue;
                        } else {
                            return n_a - n_b;
                        }
                    } else if (c_a == c_b) {
                        continue;
                    } else {
                        return c_a - c_b;
                    }
                }
                return 0;
            };
            if (vm.sortImageDirection == 0) {
               vm.reposition();
            } else {
                var map = vm.docs.reduce((a, b) => { a[b._id] = b; return a;}, {});
                vm.ids.sort((a, b) => {
                    return sortByName(map[a].baseInfo.name, map[b].baseInfo.name) * vm.sortImageDirection;
                });
                vm.docs = vm.ids.map(x => map[x]);
            }
        },
        reposition() {
            var vm = this;
            var map = vm.docs.reduce((a, b) => { a[b._id] = b; return a;}, {});

            vm.ids.splice(0, vm.ids.length);
            vm.ids.push(...vm.content);
            vm.docs = vm.ids.map(x => map[x]);
        }
    },
    watch: {
        sortGroupDirection(nv) {
            var vm = this;
            if (!vm.groupedInfo) {
                return;
            }
            vm.groupedInfo.reverse();
        },
        sortImageDirection(nv, ov) {
            var vm = this;
            if (vm.groupedInfo) {
                if (!nv) {
                    vm.reposition();
                }
                vm.groupFor(vm.groupType);
            } else {
                vm.sortForName();
            }
        },
        viewing(nv) {
            if (!nv) {
                return;
            }
            var vm = this;
            vm.scrollbar.scrollIntoView(nv.$el, {
                alignToTop: false,
                offsetBottom: 10,
                onlyScrollIfNeeded: true
            });
        },
        ids: {
            deep: true,
            handler(nv, ov) {
                var vm = this;
                var ni = [];
                // console.log(nv, ov);
                for (var i = 0; i < ov.length; i++) {
                    if (!vm.itemChosed[i]) {
                        continue;
                    }
                    var index = nv.indexOf(ov[i]);
                    if (index != -1) {
                        ni[index] = true;
                    }
                }
                vm.itemChosed = ni;
                vm.$nextTick(() => {
                    vm.getMoreUntilFullPage();
                })
            }
        },
        docs: {
            deep: true,
            handler(nv, ov) {
                var vm = this;
                if (nv === ov) {
                    vm.groupFor(vm.groupType);
                }
            }
        },
        content(nv, ov) {
            var vm = this;
            vm.ei = 0;
            vm.docs = [];
            vm.tickQueue.push(() => {
                vm.groupFor(vm.groupType);    
            });
            
        }
    },
    created() {
        var vm = this;
    },
    mounted() {
        var vm = this;
        vm.listContainer = vm.$el.querySelector('.list-container');
        vm.list = vm.listContainer.querySelector('.list');
        vm.scrollbar = Scrollbar.init(vm.listContainer);
        vm.scrollbar.addListener(function (status) {
            if (status.offset.y >= status.limit.y * 0.7) {
                vm.getMoreBackground();
            }
        });
        
        vm.after
        .add(() => {
            vm.backgroundLoading = false;
        })
        .add(vm.getMoreUntilFullPage)
        .add(_.debounce(
            () => {
                vm.$nextTick(() => {
                    window.requestAnimationFrame(() => vm.setPadding());    
                })
            }, 300
        ));

        vm.getMoreInResize = _.debounce(function() {
            vm.getMoreUntilFullPage();
            vm.setPadding();
        }, 300, { maxWait: 1000, trailing: true });
        vm.getMore();
        window.addEventListener('resize', vm.getMoreInResize);
    },
    destroyed() {
        var vm = this;
        Scrollbar.destroy(vm.listContainer);
        window.removeEventListener('resize', vm.getMoreInResize);
    }
}
</script>

<style type="text/css" scoped>

    .col-one,
    .col-two {
        width: 50% !important;
    }

    .col-one {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
    }

    .col-two {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
        left: 50%;
    }
    .controller {
        height: 3.5rem;
    }

    .list-container {
        position: relative;   
    }

    .list {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        transition: padding .5s;
    }

    .list>.item {
        width: 150px;
        height: 150px;
        overflow: hidden;
        position: relative;
    }

    .list>.item.active {
        box-shadow: 0 0 3px 3px orange;
    }

    .view-container {
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        background: rgba(0,0,0,.3);
        z-index: 20;
    }
        
    .rotate-enter-active,
    .rotate-leave-active {
        transition: all .5s;
        backface-visibility: hidden;
    }

    .rotate-enter {
        -webkit-transform: rotateY(-90deg);
           -moz-transform: rotateY(-90deg);
            -ms-transform: rotateY(-90deg);
             -o-transform: rotateY(-90deg);
                transform: rotateY(-90deg);

    }

    .rotate-leave,
    .rotate-enter-to {
        -webkit-transform: rotateY(0deg);
           -moz-transform: rotateY(0deg);
            -ms-transform: rotateY(0deg);
             -o-transform: rotateY(0deg);
                transform: rotateY(0deg);
    }

    .rotate-leave-to {
        -webkit-transform: rotateY(90deg);
           -moz-transform: rotateY(90deg);
            -ms-transform: rotateY(90deg);
             -o-transform: rotateY(90deg);
                transform: rotateY(90deg);
    }

</style>